<?php

class User {

	// Hold an instance of the class

	private $nome = '';
	private $pass = '';
	private $cookie = '';
	private $id = 0;
	private $ip = 0;
	private $remember = '';
	private $db = '';
	private $dbtable = '';
	private $administrador = 0;
	private $logado = false;
	private $empresa = 0;
	private static $_instance;

	public static function getInstance() {
		if (!(self::$_instance instanceof self)) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	// Do not allow an explicit call of the constructor: $v = new Singleton();
	final private function __construct() {

	}

	// Do not allow the clone operation: $x = clone $v;
	final private function __clone() {

	}

	public function isLogado() {
		return $this->logado;
	}

	public function utilizador($nome, $pass, $ip, $remember, $db, $dbtable) {
		$this->nome = $nome;
		$this->pass = $pass;
		$this->ip = $ip;
		$this->db = $db;
		$this->dbtable = $dbtable;
		$this->remember = $remember;
	}

	public function getnome() {
		return $this->nome;
	}

	public function getempresa() {
		return $this->empresa;
	}

	public function isAdministrador() {
		return $this->administrador;
	}

	public function actualiza_user() {
		$_SESSION['nome'] = $this->nome;
		$_SESSION['remember'] = $this->remember;
		$_SESSION['administrador'] = $this->administrador;
		$_SESSION['tuga_siga'] = $_COOKIE['tuga_siga'];
		$this->cookie = $_SESSION['tuga_siga'];

		$sql = 'UPDATE ' . $this->dbtable . '
		SET
		cookie="' . $this->cookie . '"
		WHERE id=' . $this->id;
		;
		$this->db->query($sql);

		$date = date('H:i:s d/m/Y');
		$sql = 'insert into historico values("' . $this->id . '","' . $date . '","' . $this->ip . '");';
		if (!$this->db->query($sql)) {
			die('Erro ao fazer o update');
		}
	}

	/* Cria uma nova sessaõ para o utlizador que existe na base de dados
	 * */

	public function check_user($nome, $pass, $db) {
		$sql = '
		SELECT *
		FROM ' . $this->dbtable . '
		WHERE nome=' . $nome . ' and pass=' . $pass;
		//echo $sql;
		$result = $db->getall($sql);
		//printArray($result);
		$count = $db->getcount();
		if ($count == 1) {
			$this->id = $result[0]->id;
			$this->nome = $result[0]->nome;
			$this->pass = $result[0]->pass;
			$this->empresa = $result[0]->empresa;
			$this->cookie = $result[0]->cookie;
			$this->administrador = $result[0]->administrador;
			$this->logado = true;
			$this->empresa = $result[0]->empresa;
			//echo 'ok';
			return true;
		} else {
			die('não encontrou o utilzador na base de dados');
			return false;
		}
	}

}
